import serial
import time
import signal
import sys

# 全局串口对象
ser = None

def handle_signal(signum, frame):
    global ser
    if ser is not None and ser.is_open:
        ser.close()
        print("\n串口已关闭")
    print("程序已退出，信号值: {}".format(signum))
    sys.exit(0)

signal.signal(signal.SIGINT, handle_signal)
signal.signal(signal.SIGTERM, handle_signal)

try:
    # 配置串口参数
    ser = serial.Serial(
        port='/dev/ttyAMA0',
        baudrate=115200,
        bytesize=serial.EIGHTBITS,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        timeout=1,
        xonxoff=False,
        rtscts=False
    )

    print("成功打开串口 {} (波特率: {}, 8N1)".format(ser.port, ser.baudrate))
    print("等待接收数据，按 Ctrl+C 停止...")

    while True:
        # 读取串口数据，最多读取1024字节
        data = ser.read(1024)
        if data:
            current_time = time.strftime("%H:%M:%S", time.localtime())
            bytes_read = len(data)
            print("\n[{}] 接收到 {} 字节数据：".format(current_time, bytes_read))

            # 判断是否为文本数据
            try:
                text_data = data.decode('ascii')
                # 检查是否有非打印字符（除了换行、回车、制表符）
                is_text = all(
                    (32 <= ord(c) <= 126) or (c in ['\n', '\r', '\t'])
                    for c in text_data
                )
                if is_text:
                    print("文本内容：{}".format(text_data))
                else:
                    print("十六进制：{}".format(' '.join(['{:02X}'.format(b) for b in data])))
            except UnicodeDecodeError:
                # 无法解码为ASCII，视为非文本数据
                print("十六进制：{}".format(' '.join(['{:02X}'.format(b) for b in data])))

        # 短暂延迟，降低CPU占用
        time.sleep(0.01)  # 10ms

except serial.SerialException as e:
    print("串口错误：{}".format(e))
except Exception as e:
    print("发生错误：{}".format(e))
finally:
    if ser is not None and ser.is_open:
        ser.close()
        print("串口已关闭")